<template>
  <div class="h-screen">
    <!-- 主内容区：触发按钮 -->
    <div class="trigger-wrap">
      <a-button @click="toggleDrawer" class="trigger-btn" shape="circle">
        <template #icon>
          <icon-robot />
        </template>
      </a-button>
    </div>

    <!-- 抽屉式聊天窗口 -->
    <a-drawer
      v-model:visible="drawerVisible"
      :width="420"
      title="AI 智能助手"
      placement="right"
      :footer="false"
      unmount-on-close
      class="ai-chat-drawer"
    >
      <div class="chat-container">
        <!-- 消息列表容器（带滚动条） -->
        <div class="messages-wrapper" ref="messageContainer">
          <div class="messages-header" v-if="messages.length > 0">
            <a-button
              type="text"
              size="small"
              @click="clearMessages"
              class="clear-btn"
            >
              <template #icon>
                <icon-delete />
              </template>
              清空对话
            </a-button>
          </div>

          <div v-if="messages.length === 0" class="empty-state">
            <icon-robot :size="48" />
            <p>有什么可以帮助您的？</p>
            <div class="suggestion-chips">
              <a-button
                size="small"
                @click="useQuickPrompt('帮我生成一些测试题目')"
                >帮我生成测试题目</a-button
              >
              <a-button
                size="small"
                @click="useQuickPrompt('如何使用这个系统？')"
                >如何使用系统</a-button
              >
            </div>
          </div>
          <div
            v-for="(msg, index) in messages"
            :key="index"
            :class="['message-item', msg.role]"
          >
            <div class="avatar">
              <icon-robot v-if="msg.role === 'ai'" />
              <icon-user v-else />
            </div>
            <div class="message-bubble">
              <!-- 预处理AI回复内容 -->
              <div
                class="message-content"
                v-html="formatContent(msg.content)"
              ></div>
              <div class="message-time">{{ formatTime(msg.timestamp) }}</div>
            </div>
          </div>
          <div v-if="sending" class="message-item ai">
            <div class="avatar">
              <icon-robot />
            </div>
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-area">
          <a-textarea
            v-model="inputMessage"
            placeholder="输入消息，按Enter发送..."
            @keydown.enter.prevent="sendMessage"
            :auto-size="{ minRows: 1, maxRows: 4 }"
            allow-clear
            class="chat-input"
          />
          <a-button
            type="primary"
            @click="sendMessage"
            :disabled="sending || !inputMessage.trim()"
            class="send-btn"
            shape="circle"
          >
            <template #icon>
              <icon-send />
            </template>
          </a-button>
        </div>
      </div>
    </a-drawer>
  </div>
</template>

<script setup>
import { ref, nextTick, watch, onMounted } from "vue";
import { Message, Notification } from "@arco-design/web-vue";
import { useLoginUserStore } from "@/store/userStore";
import {
  IconMessage,
  IconRobot,
  IconUser,
  IconSend,
  IconDelete,
} from "@arco-design/web-vue/es/icon";
import { chatUsingPost } from "@/api/aiChatController";

const STORAGE_KEY = "ai-chat-history";
const drawerVisible = ref(false);
const inputMessage = ref("");
const messages = ref([]);
const sending = ref(false);
const messageContainer = ref(null);
// 更新信息成功后，刷新数据
const loginUserStore = useLoginUserStore();


// 加载本地存储的聊天记录
const loadChatHistory = () => {
  try {
    const savedMessages = localStorage.getItem(STORAGE_KEY);
    if (savedMessages) {
      // 解析存储的消息并转换时间戳为Date对象
      messages.value = JSON.parse(savedMessages).map((msg) => ({
        ...msg,
        timestamp: new Date(msg.timestamp),
      }));
    }
  } catch (error) {
    console.error("加载聊天历史失败:", error);
  }
};

// 保存聊天记录到本地存储
const saveChatHistory = () => {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(messages.value));
  } catch (error) {
    console.error("保存聊天历史失败:", error);
  }
};

// 组件挂载时加载聊天记录
onMounted(() => {
  loadChatHistory();
});

// 切换抽屉状态
const toggleDrawer = () => {
  drawerVisible.value = !drawerVisible.value;
  if (drawerVisible.value) {
    nextTick(() => {
      document.querySelector(".arco-textarea-wrapper textarea")?.focus();
    });
  }
};

// 使用快速提示
const useQuickPrompt = (prompt) => {
  inputMessage.value = prompt;
  sendMessage();
};

// 清空所有消息
const clearMessages = () => {
  // 显示确认对话框
  Message.info({
    content: "对话已清空",
    duration: 2000,
  });
  messages.value = [];
  // 清空本地存储的聊天记录
  localStorage.removeItem(STORAGE_KEY);
};

// 发送消息
const sendMessage = async (e) => {
  // 如果是按Enter键但同时按了Shift，不发送，只换行
  if (e && e.shiftKey) return;

  if (!inputMessage.value.trim() || sending.value) return;

  try {
    sending.value = true;

    // 添加用户消息
    messages.value.push({
      role: "user",
      content: inputMessage.value.trim(),
      timestamp: new Date(),
    });

    // 保存并清空输入
    const userInput = inputMessage.value;
    inputMessage.value = "";

    // 保存聊天记录到本地存储
    saveChatHistory();

    // 确保滚动到底部
    await nextTick();
    scrollToBottom();

    // 调用接口
    const response = await chatUsingPost({
      userPrompt: userInput,
      model: "deepseek-v3-241226",
      systemPrompt: "你是一个智能助手",
      chatId: loginUserStore.loginUser.id
    });

    // 添加AI回复
    messages.value.push({
      role: "ai",
      content: response.data,
      timestamp: new Date(),
    });

    // 再次保存聊天记录（包含AI回复）
    saveChatHistory();
  } catch (error) {
    Notification.error({
      title: "发送失败",
      content: error.response?.data?.message || error.message || "请求失败",
    });
  } finally {
    sending.value = false;
    nextTick(() => scrollToBottom());
  }
};

// 监听消息变化，保存到本地存储
watch(
  messages,
  () => {
    if (messages.value.length > 0) {
      saveChatHistory();
    }
  },
  { deep: true }
);

// 格式化内容（处理代码块等特殊格式）
const formatContent = (content) => {
  if (!content) return "";

  // 简单处理代码块，未来可以使用markdown解析库
  const codeBlockRegex = /```([a-z]*)\n([\s\S]*?)```/g;
  return content
    .replace(/\n/g, "<br/>")
    .replace(
      codeBlockRegex,
      '<div class="code-block"><div class="code-lang">$1</div><pre>$2</pre></div>'
    );
};

// 滚动到底部
const scrollToBottom = () => {
  if (messageContainer.value) {
    messageContainer.value.scrollTop = messageContainer.value.scrollHeight;
  }
};

// 时间格式化
const formatTime = (date) => {
  return new Date(date).toLocaleTimeString([], {
    hour: "2-digit",
    minute: "2-digit",
  });
};

// 抽屉开关时自动滚动到底部
watch(drawerVisible, (newVal) => {
  if (newVal) {
    nextTick(() => scrollToBottom());
  }
});
</script>

<style scoped>
/* 容器布局 */
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

/* 消息区域 */
.messages-wrapper {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background-color: var(--color-fill-1);
  border-radius: 12px;
  margin-bottom: 16px;
  max-height: calc(100vh - 180px);
  scroll-behavior: smooth;
  box-shadow: inset 0 2px 10px rgba(0, 0, 0, 0.05);
  position: relative;
}

/* 消息头部（清空按钮区域） */
.messages-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 12px;
  position: sticky;
  top: 0;
  z-index: 10;
}

.clear-btn {
  font-size: 12px;
  color: var(--color-text-3);
  background-color: var(--color-fill-2);
  border-radius: 12px;
  padding: 2px 10px;
  transition: all 0.3s ease;
  opacity: 0.7;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
}

.clear-btn:hover {
  color: var(--color-danger);
  opacity: 1;
  transform: translateY(-2px);
  background-color: var(--color-danger-light-1);
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--color-text-3);
  height: 200px;
  gap: 16px;
  text-align: center;
}

.suggestion-chips {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  justify-content: center;
  margin-top: 8px;
}

.suggestion-chips .arco-btn {
  border-radius: 16px;
  background-color: var(--color-fill-2);
  color: var(--color-text-2);
  transition: all 0.3s ease;
}

.suggestion-chips .arco-btn:hover {
  background-color: var(--color-primary-light-1);
  color: var(--color-primary);
  transform: translateY(-2px);
}

/* 消息项 */
.message-item {
  margin: 16px 0;
  display: flex;
  gap: 12px;
  animation: fadeIn 0.3s ease-out;

  &.user {
    flex-direction: row-reverse;
  }
}

/* 头像 */
.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--color-fill-2);
  color: var(--color-text-1);
  flex-shrink: 0;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;

  .user & {
    background-color: var(--color-primary-light-1);
    color: var(--color-primary-light-4);
  }

  &:hover {
    transform: scale(1.1);
  }
}

/* 消息气泡 */
.message-bubble {
  max-width: 80%;
  padding: 12px 16px;
  border-radius: 12px;
  background-color: var(--color-bg-2);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  position: relative;
  transition: transform 0.2s ease, box-shadow 0.2s ease;

  .user & {
    background-color: var(--color-primary-light-1);
    color: var(--color-primary-dark-2);
  }

  .ai & {
    border-top-left-radius: 4px;
  }

  .user & {
    border-top-right-radius: 4px;
  }

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  }
}

/* 消息内容 */
.message-content {
  word-wrap: break-word;
  line-height: 1.6;
}

/* 代码块样式 */
:deep(.code-block) {
  background: var(--color-fill-2);
  border-radius: 8px;
  margin: 8px 0;
  overflow: hidden;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  border: 1px solid var(--color-border-2);
}

:deep(.code-lang) {
  background: var(--color-fill-3);
  padding: 4px 12px;
  font-size: 12px;
  color: var(--color-text-2);
  border-bottom: 1px solid var(--color-border-2);
  font-weight: 500;
}

:deep(.code-block pre) {
  padding: 12px;
  margin: 0;
  overflow-x: auto;
  font-family: "Menlo", "Monaco", "Courier New", monospace;
  font-size: 13px;
  line-height: 1.5;
}

/* 消息时间 */
.message-time {
  font-size: 12px;
  color: var(--color-text-3);
  text-align: right;
  margin-top: 4px;
  opacity: 0.7;
}

/* 输入区域 */
.input-area {
  display: flex;
  gap: 12px;
  padding: 16px;
  border-top: 1px solid var(--color-border-2);
  background: var(--color-bg-1);
  border-radius: 12px;
  align-items: flex-end;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.03);
}

.chat-input {
  flex: 1;
}

:deep(.arco-textarea) {
  background: var(--color-fill-1);
  border-radius: 8px;
  transition: all 0.3s ease;

  &:focus {
    box-shadow: 0 0 0 2px var(--color-primary-light-3);
    transform: translateY(-2px);
  }
}

/* 发送按钮 */
.send-btn {
  flex-shrink: 0;
  width: 40px;
  height: 40px;
  transition: all 0.3s ease;

  &:hover:not(:disabled) {
    transform: scale(1.1) rotate(15deg);
  }

  &:disabled {
    opacity: 0.6;
  }
}

/* 触发按钮 */
.trigger-wrap {
  position: fixed;
  right: 24px;
  bottom: 24px;
  z-index: 1000;

  .trigger-btn {
    width: 50px;
    height: 50px;
    background: var(--color-primary);
    color: white;
    box-shadow: 0 4px 16px rgba(var(--primary-6), 0.4);
    transition: all 0.3s ease;

    &:hover {
      transform: scale(1.1);
      box-shadow: 0 6px 20px rgba(var(--primary-6), 0.5);
    }

    &:active {
      transform: scale(0.95);
    }
  }
}

/* 打字指示器 */
.typing-indicator {
  display: flex;
  align-items: center;
  background: var(--color-bg-2);
  padding: 12px 16px;
  border-radius: 12px;
  border-top-left-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  span {
    display: inline-block;
    width: 8px;
    height: 8px;
    margin-right: 5px;
    background: var(--color-text-3);
    border-radius: 50%;
    opacity: 0.4;
    animation: typing 1.4s infinite;

    &:nth-child(1) {
      animation-delay: 0s;
    }

    &:nth-child(2) {
      animation-delay: 0.2s;
    }

    &:nth-child(3) {
      animation-delay: 0.4s;
      margin-right: 0;
    }
  }
}

/* 抽屉样式 */
:deep(.ai-chat-drawer .arco-drawer-header) {
  border-bottom: 1px solid var(--color-border-2);
  padding: 16px 20px;
}

:deep(.ai-chat-drawer .arco-drawer-title) {
  font-weight: 600;
  font-size: 16px;
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.ai-chat-drawer .arco-drawer-title)::before {
  content: "";
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color: var(--color-primary);
  border-radius: 50%;
  box-shadow: 0 0 0 3px var(--color-primary-light-3);
}

:deep(.ai-chat-drawer .arco-drawer-body) {
  padding: 16px;
}

/* 动画 */
@keyframes typing {
  0% {
    transform: translateY(0px);
    opacity: 0.4;
  }
  50% {
    transform: translateY(-5px);
    opacity: 0.8;
  }
  100% {
    transform: translateY(0px);
    opacity: 0.4;
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  :deep(.ai-chat-drawer) {
    width: 100% !important;
  }

  .message-bubble {
    max-width: 85%;
  }
}
</style>
